package cn.jesin.css.controller;

import cn.hutool.core.util.StrUtil;
import cn.jesin.css.common.DefaultPassword;
import cn.jesin.css.common.Flag;
import cn.jesin.css.service.UserService;
import cn.jesin.css.vo.OtherAuthInfo;
import cn.jesin.css.vo.UserInfo;
import cn.jesin.css.vo.responseformat.Code;
import cn.jesin.css.vo.responseformat.Result;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.*;

/**
 * @author 谷汉斌
 * @description
 * @createTime 2024/8/13 下午11:07
 */
@Tag(name = "用户控制器", description = "处理普通用户/管理员的请求")
@RestController
@RequestMapping("/users")
public class UserController {

    @Resource
    private UserService userService;

    /**
     * 绑定手机号或者邮箱等其他第三方账号
     */
    @Operation(summary = "绑定手机号或者邮箱等其他第三方账号")
    @PostMapping("/bind")
    public Result<Object> bind(@RequestBody OtherAuthInfo otherAuthInfo) {
        if (otherAuthInfo != null) {
            boolean res = userService.bind(otherAuthInfo);
            return Result.builder().code(res ? Code.BIND_SUCCESS.getCode() : Code.BIND_FAIL.getCode())
                    .flag(res ? Flag.SUCCESS.isCode() : Flag.FAIL.isCode())
                    .message(res ? Code.BIND_SUCCESS.getInfo() : Code.BIND_FAIL.getInfo())
                    .build();
        }
        return Result.builder().code(Code.BIND_FAIL.getCode())
                .flag(Flag.FAIL.isCode())
                .message(Code.BIND_FAIL.getInfo())
                .build();
    }

    /**
     * 设置/更新密码
     */
    @Operation(summary = "设置/更新密码")
    @PostMapping("/update-password")
    public Result<Object> updatePassword(@RequestParam(value = "oldPassword", defaultValue = DefaultPassword.PASSWORD) String oldPassword,
                                         @RequestParam(value = "newPassword") String newPassword) {
        boolean res = false;
        if (StrUtil.isNotBlank(oldPassword) || StrUtil.isNotBlank(newPassword)) {
            res = userService.updatePassword(oldPassword, newPassword);
        }
        return Result.builder().code(res ? Code.UPDATE_SUCCESS.getCode() : Code.UPDATE_FAIL.getCode())
                .flag(res ? Flag.SUCCESS.isCode() : Flag.FAIL.isCode()).message(res ? Code.UPDATE_SUCCESS.getInfo() : Code.UPDATE_FAIL.getInfo())
                .build();
    }


    /**
     * 获取登录的用户信息
     */
    @Operation(summary = "获取登录的用户信息")
    @GetMapping("/login-info")
    public Result<UserInfo> getUserInfo() {
        UserInfo userInfo = userService.getLoginUserInfo();
        return Result.<UserInfo>builder().code(Code.QUERY_SUCCESS.getCode())
                .flag(Flag.SUCCESS.isCode())
                .message(Code.QUERY_SUCCESS.getInfo())
                .data(userInfo).build();
    }

}
